package com.hjq.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.IdRes
import androidx.fragment.app.Fragment

/**
 * LazyFragment,fragment懒加载
 */
abstract class LazyFragment : Fragment(){
    /** 根布局 */
    private var rootView: View? = null

    // 标志位 标志已经初始化完成。
    protected var isPrepared: Boolean = false

    //标志位 fragment是否可见
    protected var isPageVisible: Boolean = false

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        if (getLayoutId() <= 0) {
            return null
        }
        rootView = inflater.inflate(getLayoutId(), container, false)
        initView()
        return rootView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        finishCreateView(savedInstanceState)
    }

    /**
     * 初始化views
     *
     * @param state
     */
    fun finishCreateView(state: Bundle?) {
        isPrepared = true
        prepareLazyLoad()
    }

    private fun prepareLazyLoad() {
        if (!isPrepared || !isPageVisible) {
            return
        }
        lazyLoad()
        isPrepared = false
    }

    /**
     * Fragment数据的懒加载
     */
    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (userVisibleHint) {
            isPageVisible = true
            onVisible()
        } else {
            isPageVisible = false
            onInvisible()
        }
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden) {
            isPageVisible = true
            onVisible()
        } else {
            isPageVisible = false
            onInvisible()
        }
    }

    /**
     * fragment显示时才加载数据
     */
    protected fun onVisible() {
        prepareLazyLoad()
    }

    /**
     * fragment隐藏
     */
    protected fun onInvisible() {
    }

    /**
     * fragment懒加载方法
     */
    open fun lazyLoad() {
    }


    /**
     * 获取布局 ID
     */
    protected abstract fun getLayoutId(): Int

    /**
     * 初始化控件
     */
    protected abstract fun initView()

    /**
     * 根据资源 id 获取一个 View 对象
     */
    fun <V : View?> findViewById(@IdRes id: Int): V? {
        return rootView?.findViewById(id)
    }
}